package com.ssm.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.entity.SysRole;
import com.ssm.entity.SysRolePer;
import com.ssm.service.SysRolePerService;
import com.ssm.service.SysRoleService;
import com.ssm.service.SysUserRoleService;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * (SysRole)表控制层
 *
 * @author makejava
 * @since 2021-06-02 13:55:23
 */
@RestController
@RequestMapping("sysRole")
public class SysRoleController {
    /**
     * 服务对象
     */
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysRolePerService sysRolePerService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public SysRole selectOne(Integer id) {
        return this.sysRoleService.queryById(id);
    }

    @RequestMapping("selectJson")
    public PageInfo<SysRole> queryAll(SysRole sysRole, Integer rows, Integer page){
        PageHelper.startPage(page,rows);
        List<SysRole> list = sysRoleService.queryAll(sysRole);
        PageInfo<SysRole> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
    @PostMapping("add")
    public String addSysRole(@Validated @RequestBody SysRole sysRole, BindingResult bindingResult, Model model){

        if(bindingResult.hasErrors()) {
            //数据验证没有全部通过
            List<ObjectError> list = bindingResult.getAllErrors();
            for (ObjectError objectError:list){
                System.out.println(objectError.getDefaultMessage());
            }
            model.addAttribute("errors", list);
                return "failure";
        }

        List<SysRole> sysRoles = sysRoleService.queryAll(sysRole);
        if (sysRoles.isEmpty()){
            sysRole.setCreateTime(new Date());
            sysRole.setUpdateTime(new Date());
            sysRoleService.insert(sysRole);

            Integer[] integers = new Integer[]{1,2,3,4,5,6};
            SysRolePer sysRolePer = new SysRolePer();
            sysRolePer.setRoleId(sysRole.getId());
            for (Integer i:integers){
                sysRolePer.setPerId(i);
                sysRolePerService.insert(sysRolePer);
            }
            return "success";
        }
        return "repet";

    }
    @RequestMapping("delete/{id}")
    public String deleteSysRole(@PathVariable Integer id){
        sysRoleService.deleteById(id);
        return "success";
    }

    @RequestMapping("dels/{ids}")
    public String deleteSysRoles(@PathVariable Integer[] ids){
        sysRoleService.deleteRoles(ids);
        return "success";
    }
}
